<?php
namespace App\Library;

class Common {

    /**
     * @param $data
     * @param string $secret
     * @return string
     */
    public static function getSign($data,$secret = '') {
        if (empty($secret)) {
            $secretKey  = CommonConst::SIGN_SECRET_KEY;
        } else {
            $secretKey = $secret;
        }
        ksort($data);
        $signData = array();
        foreach ($data as $k => $v) {
            if (empty($v)  && $v != 0) {
                continue;
            }
            $signData[$k] = $v;
        }
        $dataSign  = http_build_query($signData);
        $stringSignTemp = $dataSign.'&key='.$secretKey;
        $sign = strtoupper(md5($stringSignTemp));
        return $sign;
    }

    /**
     * @param $data
     * @param $fileName
     * @return bool
     * @desc 延签
     */
    public static function checkSign($data,$fileName) {
        if (!isset($data['sign'])) {
            return false;
        }
        $sign = $data['sign'];
        unset($data['sign']);
        if (isset($data['server_name'])) {
            unset($data['server_name']);
        }
        if (isset($data['role_name'])) {
            unset($data['role_name']);
        }
        $serverSign = self::getSign($data);
        Log::logInfo('sign',['sign' => $sign,'server_sign' => $serverSign],$fileName);
        if ($serverSign == $sign) {
            return true;
        }
        return false;
    }

    /**
     * @desc 获取当天剩余过期时间
     */
    public static function getRemain() {
        return strtotime('23:59:59') - time();
    }

    /**
     * @desc 生成唯一ID作为traceId
     * @return string
     */
    public static function getTraceId() {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime()*10000);
            $charid = md5(uniqid(rand(), true));
            $uuid = substr($charid, 0, 8)
                .substr($charid, 8, 4)
                .substr($charid,12, 4)
                .substr($charid,16, 4)
                .substr($charid,20,12);
            return $uuid;
        }
    }

    /**
     * @desc ip白名单
     * @param string $ip
     * @return bool
     */
    public static function checkIp($ip) {

    }
}
